
// export const fetcher = async <T>(url: string): Promise<T> => {

import { redirect, useNavigate, useNavigation } from "react-router";

//     const token = localStorage.getItem('token');


//     const response = await fetch(url, {
//         headers: {
//             "Authorization": `Bearer ${token}`
//         },
//     });
//     if (!response.ok) {
//         throw new Error(`HTTP error: Status ${response.status}`);
//     }
//     return await response.json();
// };

export async function fetcher<T>(
    url: string,
    options: RequestInit = {}
  ): Promise<T> {


    // 请求拦截器
    const requestOptions: RequestInit = {
      ...options,
      headers: {
        ...options.headers,
        Authorization: `Bearer ${localStorage.getItem('idToken')}`, // 添加 token
      },
    };
  
    try {
      const response = await fetch(url, requestOptions);
  
      if (!response.ok) {
        if (response.status === 401) {
          // 处理未授权情况

        // refresh token
        //   todo
        redirect("/login");
        }
        // throw new Error(`HTTP error! status: ${response.status}`);
      }
  
      const data: T = await response.json();
      return data;
    } catch (error) {
     
      throw error; // 重新抛出错误，以便调用者处理
    }
  }
  
  // 使用自定义的 fetch 函数
//   async function fetchData() {
//     try {
//       const data = await customFetch<{ message: string }>('/api/data');
//       console.log(data);
//     } catch (error) {
//       // 处理错误
//     }
//   }
  
//   fetchData();